package com.winit.cloudlink.message.utils;

import com.alibaba.fastjson.JSON;
import com.google.common.io.Files;
import com.winit.cloudlink.message.Message;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.util.Date;

public class FileMessageWriter implements MessageWriter, Closeable {
	private static final Logger logger = LoggerFactory.getLogger(FileMessageWriter.class);
	public static final String separator = "_";
	public static final String fileExtension = ".bak";

	private String backupDir;
	private Writer output;

	public FileMessageWriter() {
		this.backupDir = getDefaultBackupDir();
	}

	public FileMessageWriter(String backupDir) {
		this.backupDir = backupDir;
	}

	public String getBackupDir() {
		return backupDir;
	}

	@Override
	public void write(Message message) throws IOException {
		if (output == null) {
			File backFile = new File(backupDir, "SendFailure" + fileExtension);
			if (!backFile.exists()) {
				Files.createParentDirs(backFile);
			}
			output = new FileWriter(backFile, true);
		}
		String messsageJson = JSON.toJSONString(message);
		output.append(messsageJson + "\r\n");
		output.flush();
	}


	@Override
	public void close() throws IOException {
		if (output != null) {
			output.close();
		}
	}


	private String getDefaultBackupDir() {
		StringBuffer filename = new StringBuffer();
		filename.append(System.getProperty("user.home"))
				.append(File.separator).append(".cloudlink")
				.append(File.separator).append("backup");
		return filename.toString();
	}

	private static class MessageWrapper implements Serializable {
		private Message message;
		private Date created;

		public MessageWrapper() {
			this.created = new Date();
		}

		public MessageWrapper(Message message) {
			this.message = message;
			this.created = new Date();
		}

		public MessageWrapper(Message message, Date created) {
			this.message = message;
			this.created = created;
		}

		public Message getMessage() {
			return message;
		}

		public void setMessage(Message message) {
			this.message = message;
		}

		public Date getCreated() {
			return created;
		}

		public void setCreated(Date created) {
			this.created = created;
		}
	}
}
